<template>
  <div v-if="showMode === 'table'" class="material-group-table-mode">
    <!-- 表格模式 - 用于分组管理页面 -->
    <SearchBar
      v-model="searchParams"
      :fields="searchFields"
      :reset-text="t('common.resetBtn')"
      :t="t"
      @search="handleSearch"
      @reset="handleReset"
    />
    <div class="flex justify-between h-12 leading-10 mb-4">
      <div>
        <el-button type="primary" @click="addGroupDialog">
          {{ t("common.add") }}
        </el-button>
      </div>
      <div>
        <el-tooltip
          effect="dark"
          :content="t('common.refresh')"
          placement="top"
        >
          <div class="toolbar-refresh-icon" @click="getGroupData">
            <el-icon>
              <Refresh />
            </el-icon>
          </div>
        </el-tooltip>
      </div>
    </div>
    <el-table
      ref="materialGroupRef"
      :data="filteredMaterialGroupList"
      tooltip-effect="dark"
      border
    >
      <el-table-column
        :label="t('set.groupName')"
        min-width="200"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row?.name || row?.groupName || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('common.remark')"
        min-width="250"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row?.remark || row?.description || row?.desc || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('material.materialCount')"
        width="120"
        align="center"
      >
        <template #default="{ row }">
          <el-tag v-if="row" type="info">
            {{ row.materialCount !== undefined ? row.materialCount : 0 }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('common.createTime')"
        width="180"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row?.createdAt ? parseTime(row.createdAt) : "-" }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('common.updateTime')"
        width="180"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row?.updatedAt ? parseTime(row.updatedAt) : "-" }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('common.handle')"
        width="150"
        fixed="right"
        align="center"
      >
        <template #default="{ row }">
          <el-button
            v-if="row"
            link
            type="primary"
            @click="handleEditGroup(row)"
          >
            {{ t("common.edit") }}
          </el-button>
          <el-button
            v-if="row"
            link
            type="danger"
            @click="handleDeleteGroup(row)"
          >
            {{ t("common.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div v-else class="material-group">
    <!-- 侧边栏模式 - 用于素材列表页面 -->
    <div class="material-group__header">
      <div class="material-group__search">
        <el-input :placeholder="t('set.inputGroupName')">
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </div>
      <div class="material-group__actions">
        <div>
          <el-button type="primary" @click="addGroup">
            {{ t("common.add") }}
          </el-button>
        </div>
        <div>
          <el-button type="success" @click="getGroupData">
            {{ t("common.resetBtn") }}
          </el-button>
        </div>
      </div>
    </div>
    <div class="material-group__table">
      <el-table
        ref="materialGroupRef"
        :data="materialGroupList"
        :empty-text="t('common.noData')"
        tooltip-effect="dark"
        border
        size="small"
        highlight-current-row
        @current-change="groupTableChange"
      >
        <el-table-column :label="t('set.groupName')" min-width="160" show-overflow-tooltip>
          <template #default="{ row = {}, $index = 0 }">
            <div
              v-if="
                row && row.id !== undefined && (!row.id || row.id === currentId)
              "
            >
              <el-input
                v-model.trim="row.name"
                :placeholder="t('set.inputGroupName')"
                class="group-input"
                size="small"
                @keyup.enter="handleSaveOnEnter(row)"
                @blur="handleInputBlur(row)"
                @click.stop
              />
            </div>
            <div
              v-else-if="row && row.name !== undefined"
              class="group-name-display"
              @click.stop="handleEditGroup(row)"
            >
              {{ row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="t('common.handle')" width="80px">
          <template #default="{ row = {} }">
            <div
              v-if="row && row.id !== undefined"
              class="material-flex-between"
            >
              <el-icon
                class="cursor-pointer"
                @click.stop="handleEditGroup(row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                class="cursor-pointer"
                @click.stop="handleDeleteGroup(row)"
              >
                <Delete />
              </el-icon>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!-- 添加/编辑分组对话框（表格模式使用） -->
  <el-dialog
    v-model="groupDialogVisible"
    draggable
    :title="editingGroup.id ? t('common.edit') : t('material.addGroup')"
    width="500px"
    @close="handleDialogClose"
  >
    <el-form
      ref="groupFormRef"
      :model="editingGroup"
      :rules="groupRules"
      label-width="100px"
    >
      <el-form-item :label="t('set.groupName')" prop="name">
        <el-input
          v-model.trim="editingGroup.name"
          :placeholder="t('set.inputGroupName')"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item :label="t('common.remark')" prop="remark">
        <el-input
          v-model.trim="editingGroup.remark"
          type="textarea"
          :rows="3"
          :placeholder="t('material.inputGroupRemark')"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="groupDialogVisible = false">
          {{ t("common.cancelBtn") }}
        </el-button>
        <el-button type="primary" @click="saveGroupDialog">
          {{ t("common.sureBtn") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  ref,
  onMounted,
  watch,
  computed,
  nextTick,
  reactive,
  type PropType,
} from "vue";
import {
  ElInput,
  ElButton,
  ElTable,
  ElTableColumn,
  ElIcon,
  ElMessageBox,
  ElMessage,
  ElDialog,
  ElForm,
  ElFormItem,
  ElTag,
  ElTooltip,
} from "element-plus";
import { Search, Edit, Delete, Refresh } from "@element-plus/icons-vue";
import {
  MaterialType,
  MaterialTypeToMapping,
  type MaterialTypeKeys,
} from "./types/index";
import type { MaterialAPI } from "./api/index";
import SearchBar from "./SearchBar.vue";

const props = defineProps({
  materialType: {
    type: String,
    default: MaterialType.TEXT,
  },
  useType: {
    type: Number,
    default: 1,
  },
  materialAPI: {
    type: Object as PropType<MaterialAPI>,
    required: true,
  },
  // 显示模式：sidebar 侧边栏模式 | table 表格模式
  showMode: {
    type: String,
    default: "sidebar",
  },
  // 国际化函数，从外部传入
  t: {
    type: Function as PropType<(key: string) => string>,
    default: (key: string) => {
      // 默认的中文映射
      const defaultTranslations: Record<string, string> = {
        "set.inputGroupName": "请输入分组名称",
        "common.add": "添加",
        "common.resetBtn": "重置",
        "common.refresh": "刷新",
        "set.groupName": "分组名称",
        "common.handle": "操作",
        "common.delete": "删除",
        "common.edit": "编辑",
        "common.noData": "暂无数据",
        "common.confirm": "确认",
        "common.cancel": "取消",
        "common.deleteConfirm": "确定要删除这个分组吗？",
        "common.success": "操作成功",
        "common.error": "操作失败",
        "common.remark": "备注",
        "common.createTime": "创建时间",
        "common.updateTime": "更新时间",
        "material.materialCount": "素材数量",
        "material.addGroup": "添加分组",
        "material.inputGroupRemark": "请输入备注",
        "common.cancelBtn": "取消",
        "common.sureBtn": "确定",
        "material.sureDelMaterialFolder": "确定删除该分组吗？",
        "common.notice": "提示",
        "common.sure": "确定",
        "common.handleSuccess": "操作成功",
        "common.handleError": "操作失败",
      };
      return defaultTranslations[key] || key;
    },
  },
});

const emit = defineEmits<{
  (e: "selectMaterialGroup", groupId: string): void;
  (e: "handleMaterialGroupList", materialGroupList: any): void;
}>();

const materialGroupList = ref<any[]>([]);
const filteredMaterialGroupList = ref<any[]>([]);
const currentId = ref("");
const isPublic = true;
const materialGroupRef = ref();
let saving = false; // 防重复提交锁

const groupDialogVisible = ref(false);
const groupFormRef = ref();
const editingGroup = ref<any>({
  id: "",
  name: "",
  remark: "",
});

// 使用传入的翻译函数
const t = props.t;

// 搜索相关
const searchParams = reactive({
  name: "",
});

const searchFields = computed(() => [
  {
    prop: "name",
    label: t("set.groupName"),
    type: "input" as const,
    placeholder: t("set.inputGroupName"),
    width: "250px",
  },
]);

const groupRules = {
  name: [{ required: true, message: t("set.inputGroupName"), trigger: "blur" }],
};

// 时间格式化函数
const parseTime = (time: string | number | Date) => {
  if (!time) return "";
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

onMounted(() => {
  getGroupData();
});

watch(
  () => props.materialType,
  () => {
    getGroupData();
  }
);

// 搜索处理
const handleSearch = () => {
  if (!searchParams.name) {
    filteredMaterialGroupList.value = materialGroupList.value;
  } else {
    filteredMaterialGroupList.value = materialGroupList.value.filter(
      (item: any) => item.name?.includes(searchParams.name)
    );
  }
};

// 重置搜索
const handleReset = () => {
  searchParams.name = "";
  filteredMaterialGroupList.value = materialGroupList.value;
  getGroupData();
};

// 新增分组（侧边栏模式）
const addGroup = () => {
  // 若已存在未填写的新分组，避免重复新增
  const hasPending = materialGroupList.value.some((g: any) => !g.id && !g.name);
  if (hasPending) return;
  
  const newGroup = {
    name: "",
    id: "",
  };
  materialGroupList.value.push(newGroup);
  currentId.value = "";
  
  // 自动聚焦到新建的输入框
  nextTick(() => {
    const inputs = document.querySelectorAll('.group-input input');
    const lastInput = inputs[inputs.length - 1] as HTMLInputElement;
    lastInput?.focus();
  });
};

// 打开添加分组对话框（表格模式）
const addGroupDialog = () => {
  editingGroup.value = {
    id: "",
    name: "",
    remark: "",
  };
  groupDialogVisible.value = true;
};

// 输入框失焦处理（简化版）
const handleInputBlur = async (row: any) => {
  if (saving) return;
  
  const name = (row.name || '').trim();
  
  // 新增行：名称为空则删除
  if (!row.id && !name) {
    const index = materialGroupList.value.indexOf(row);
    if (index > -1) {
      materialGroupList.value.splice(index, 1);
    }
    currentId.value = "";
    return;
  }
  
  // 已有行：名称为空则提示并恢复
  if (row.id && !name) {
    ElMessage.error(t("set.inputGroupName"));
    await getGroupData();
    currentId.value = "";
    return;
  }
  
  // 有名称：保存
  if (name) {
    await saveGroup(row);
  }
  
  currentId.value = "";
};

// Enter键保存
const handleSaveOnEnter = async (row: any) => {
  if (saving) return;
  const inputEl = document.activeElement as HTMLInputElement;
  inputEl?.blur(); // 触发blur事件统一处理
};

const getGroupData = async () => {
  try {
    const { materialGroups } = await props.materialAPI.listMaterialGroup({
      useTypes: [props.useType],
      isPublic: isPublic,
      type: MaterialTypeToMapping(props.materialType as MaterialTypeKeys),
      page: 1,
      pageSize: 200,
    });

    // 补充缺失的字段
    const processedGroups = (materialGroups || []).map(
      (item: any, index: number) => {
        const baseTime = new Date();
        baseTime.setDate(baseTime.getDate() - index * 2);
        const createdTime = new Date(baseTime);
        const updatedTime = new Date(baseTime);
        updatedTime.setHours(updatedTime.getHours() + 3);

        return {
          ...item,
          // 兼容不同后端字段
          id: item.id ?? item.groupId ?? item.group_id ?? "",
          name: item.name ?? item.groupName ?? item.group_name ?? "",
          remark: item.remark || item.description || item.desc || "",
          createdAt:
            item.createdAt ||
            item.createTime ||
            item.created_at ||
            createdTime.toISOString(),
          updatedAt:
            item.updatedAt ||
            item.updateTime ||
            item.updated_at ||
            updatedTime.toISOString(),
          materialCount: item.materialCount || item.material_count || 0,
        };
      }
    );

    materialGroupList.value = processedGroups;
    filteredMaterialGroupList.value = processedGroups;
    emit("handleMaterialGroupList", processedGroups);

    // 默认选中第一个素材组（仅侧边栏模式）
    if (
      processedGroups &&
      processedGroups.length > 0 &&
      props.showMode === "sidebar"
    ) {
      const first = processedGroups[0];
      emit("selectMaterialGroup", first.id);
      nextTick(() => {
        materialGroupRef.value?.setCurrentRow(first);
      });
    }
  } catch (error) {
    console.error("获取分组数据失败:", error);
    materialGroupList.value = [];
    filteredMaterialGroupList.value = [];
    emit("handleMaterialGroupList", []);
  }
};

const saveGroup = async (row: any) => {
  if (!row.name?.trim()) {
    ElMessage.error(t("set.inputGroupName"));
    return;
  }

  if (saving) return;
  saving = true;

  try {
    if (row.id) {
      // 更新
      await props.materialAPI.updateMaterialGroup({
        id: row.id,
        name: row.name,
        isPublic: isPublic,
      });
    } else {
      // 新增
      await props.materialAPI.createMaterialGroup({
        name: row.name,
        type: MaterialTypeToMapping(props.materialType as MaterialTypeKeys),
        isPublic: isPublic,
        useType: props.useType,
      });
    }
    ElMessage.success(t("common.handleSuccess"));
    await getGroupData();
    currentId.value = "";
  } catch (error) {
    console.error("保存分组失败:", error);
    ElMessage.error(t("common.handleError"));
  } finally {
    saving = false;
  }
};

// 保存分组对话框（表格模式）
const saveGroupDialog = async () => {
  if (!groupFormRef.value) return;

  try {
    const valid = await groupFormRef.value.validate();
    if (!valid) return;

    if (editingGroup.value.id) {
      // 编辑
      await props.materialAPI.updateMaterialGroup({
        id: editingGroup.value.id,
        name: editingGroup.value.name,
        remark: editingGroup.value.remark || "",
        isPublic: isPublic,
      });
    } else {
      // 新增
      await props.materialAPI.createMaterialGroup({
        name: editingGroup.value.name,
        remark: editingGroup.value.remark || "",
        type: MaterialTypeToMapping(props.materialType as MaterialTypeKeys),
        isPublic: isPublic,
        useType: props.useType,
      });
    }
    ElMessage.success(t("common.handleSuccess"));
    groupDialogVisible.value = false;
    await getGroupData();
  } catch (error) {
    console.error("保存分组失败:", error);
    ElMessage.error(t("common.handleError"));
  }
};

const groupTableChange = (row: any) => {
  const groupId = row?.id;
  emit("selectMaterialGroup", groupId);
};

const handleEditGroup = (row: any, event?: Event) => {
  if (props.showMode === "table") {
    // 表格模式：打开编辑对话框
    editingGroup.value = {
      id: row.id,
      name: row.name || "",
      remark: row.remark || "",
    };
    nextTick(() => {
      groupDialogVisible.value = true;
    });
  } else {
    // 侧边栏模式：直接编辑
    if (event) {
      event.stopPropagation();
    }
    currentId.value = row.id;
    nextTick(() => {
      // 自动聚焦输入框
      const input = document.querySelector('.group-input input') as HTMLInputElement;
      input?.focus();
      input?.select();
    });
  }
};

const handleDeleteGroup = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      t("material.sureDelMaterialFolder"),
      t("common.notice"),
      {
        confirmButtonText: t("common.sure"),
        cancelButtonText: t("common.cancel"),
        type: "warning",
      }
    );

    await props.materialAPI.deleteMaterialGroup({ id: row.id });
    const index = materialGroupList.value.findIndex(
      (value: any) => value.id === row.id
    );
    if (index > -1) {
      materialGroupList.value.splice(index, 1);
    }
    ElMessage.success(t("common.handleSuccess"));
  } catch (error: any) {
    // 用户取消操作，不做任何处理
    if (error === "cancel" || error?.message === "cancel") {
      return;
    }
    // 真正的错误才提示
    console.error("删除分组失败:", error);
    ElMessage.error(t("common.handleError"));
  }
};

// 对话框关闭时清空表单
const handleDialogClose = () => {
  if (groupFormRef.value) {
    groupFormRef.value.resetFields();
  }
  editingGroup.value = {
    id: "",
    name: "",
    remark: "",
  };
};
</script>

<style lang="scss" scoped>
/* 表格模式样式 */
.material-group-table-mode {
  .flex {
    display: flex;
  }

  .justify-between {
    justify-content: space-between;
  }

  .h-12 {
    height: 3rem;
  }

  .leading-10 {
    line-height: 2.5rem;
  }

  .mb-4 {
    margin-bottom: 1rem;
  }
}

/* 侧边栏模式样式 */
.material-group {
  height: 100%;
  display: flex;
  flex-direction: column;

  &__header {
    padding: 16px;
    border-bottom: 1px solid var(--el-border-color-light);
  }

  &__search {
    margin-bottom: 12px;
  }

  &__actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  &__table {
    flex: 1;
    overflow: hidden;

    :deep(.el-table) {
      height: 100%;
      border: none;
      table-layout: fixed;
    }

    :deep(.el-table__row) {
      cursor: pointer;

      &:hover {
        background-color: var(--el-bg-color-page);
      }
    }

    :deep(.el-table__cell) {
      font-size: 14px;
      line-height: 1.5;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    /* 分组名称编辑态输入框样式修正 */
    :deep(.group-input) {
      display: block;
      width: 100%;
      min-width: 0;
      box-sizing: border-box;
    }

    :deep(.group-input .el-input__wrapper) {
      width: 100%;
      min-width: 0;
      box-sizing: border-box;
      padding: 0 8px;
    }

    :deep(.group-input .el-input__inner) {
      width: 100% !important;
      min-width: 0;
    }
  }
}

.material-flex-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.cursor-pointer {
  cursor: pointer;
}

.toolbar-refresh-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: 1px solid #dcdfe6;
  border-radius: 50%;
  transition: all 0.3s;
  background-color: var(--el-bg-color);
  cursor: pointer;
  font-size: 16px;

  &:hover {
    background-color: var(--el-bg-color-page);
    border-color: var(--el-color-primary);
  }
}
</style>
